package com.concurrency.practise.service;

import com.concurrency.practise.entity.Dog;
import com.concurrency.practise.entity.repository.DogRepository;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @program: currency_practise
 * @description:
 * @author: Jiliang.Lee
 * @create: 2019-12-12 11:00
 **/
@Service
@AllArgsConstructor
@Slf4j
@CacheConfig(cacheNames = "cache0")
public class DogService {
	private final DogRepository dogRepository;
	private final DogQueryService dogQueryService;

	@CachePut(key = "#id")
	public Dog buyDog(Long id) throws Exception {
		Dog dog = dogQueryService.getDog(id);
		log.info(this.toString());
		log.info("找到了" + dog.getStoreNumber());
		if (dog.getStoreNumber() > 0) {
			dog.setStoreNumber(dog.getStoreNumber() - 1);
			log.info("还剩下" + dog.getStoreNumber());
		} else {
			throw new Exception("库存不足");
		}
		return dog;
	}

	@Transactional
	public Dog buyDogWithDB(Long id) {
		Dog dog = dogRepository.findById(id).get();
		log.info(this.toString());
		log.info("找到了" + dog.getStoreNumber());
		dog.setStoreNumber(dog.getStoreNumber() - 1);
		log.info("还剩下"+ dog.getStoreNumber());
		return dog;
	}

}
